<template>
  <div class="bottom-popup-container" :class="{ collapsed: !isExpanded }">
    <!-- 使用单个容器包裹所有项目，并使用flexbox进行布局 -->
    <div v-if="isExpanded" class="items-container">
      <!-- 添加一个用于ECharts图表的div，并使用ref绑定到chartRef -->
      <div ref="chartRef" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { useEchartsStore } from "@/stores/echartsStore";

const props = defineProps({
  isExpanded: Boolean,
});

const emit = defineEmits(["update:isExpanded"]);

const localIsExpanded = ref(props.isExpanded);

// 初始化数据
const chartRef = ref(null); // 用于存储对DOM元素的引用
const echartsStore = useEchartsStore();

watch(
  () => props.isExpanded,
  (newValue) => {
    localIsExpanded.value = newValue;
  }
);

onMounted(() => {
  if (localIsExpanded.value) {
    initChart(); // 如果初始状态是展开，则初始化图表
  }
});

watch(localIsExpanded, (newValue) => {
  if (newValue) {
    nextTick(() => {
      initChart(); // 当弹出框展开时重新初始化图表
    });
  } else {
    disposeChart(); // 当弹出框关闭时销毁图表
  }
});

onUnmounted(() => {
  disposeChart(); // 组件卸载时销毁图表
});

// 初始化图表
function initChart() {
  if (!localIsExpanded.value) return;
  echartsStore.initChart(chartRef.value);
}

// 销毁图表实例以避免内存泄漏
function disposeChart() {
  echartsStore.disposeChart();
}
</script>

<style scoped>
/* 样式保持不变 */
.bottom-popup-container {
  width: 69%;
  max-height: 35vh; /* 根据需要调整 */
  position: fixed;
  bottom: 5%;
  left: 15%;
  right: 15%;
  z-index: 1000;
  background-color: rgba(24, 44, 70, 0.8); /* 半透明背景色，深邃的科技蓝 */
  border-radius: 0 0 10px 10px; /* 上侧圆角 */
  display: flex;
  flex-direction: column-reverse; /* 内容从底部开始 */
  transition: transform 0.3s ease-in-out, max-height 0.3s ease-in-out; /* 添加过渡效果 */
}

.items-container {
  width: 98%;
  max-height: 30vh;
  height: auto;
  display: flex;
  flex-direction: column;
  gap: 8px; /* 为每一行之间的间距 */
  padding: 10px; /* 内边距 */
}

.chart-container {
  width: 100%;
  height: 40vh;
  background-color: rgba(
    255,
    255,
    255,
    0.1
  ); /* 半透明白色背景，与整体色调协调 */
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px; /* 圆角 */
}

.toggle-button {
  position: absolute;
  top: -34px; /* 将按钮放置在容器顶部上方 */
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  border-radius: 4px;
  padding: 10px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: top 0.3s ease-in-out, background-color 0.3s ease;
}

.toggle-button:hover {
  background-color: rgba(255, 255, 255, 1);
}

.collapsed {
  transform: translateY(100%); /* 容器向下移动自身高度 */
  max-height: 0; /* 收缩容器高度 */
}
</style>
